<template>
    <div class="store-list-container">
        <!-- 顶部导航栏 -->
        <div class="navbar">
            <div class="navbar-title">宠物商店</div>
            <router-link to="/store/nearby" class="text-primary">
                <i class="fas fa-map-marker-alt"></i>
            </router-link>
        </div>

        <!-- 搜索栏 -->
        <div class="header">
            <div class="search-bar">
                <i class="fas fa-search search-icon"></i>
                <input type="text" class="search-input" placeholder="搜索宠物店" v-model="searchQuery" @input="handleSearch">
            </div>
        </div>

        <!-- 过滤栏 -->
        <div class="filter-bar">
            <div v-for="filter in filters" :key="filter.value"
                :class="['filter-btn', { active: currentFilter === filter.value }]" @click="setFilter(filter.value)">
                {{ filter.name }}
            </div>
        </div>

        <!-- 商店列表 -->
        <div class="container store-list">
            <div v-if="loading" class="loading-container">
                <div class="loading-spinner"></div>
                <div class="loading-text">加载中...</div>
            </div>

            <div v-else-if="filteredStores.length === 0" class="empty-state">
                <i class="fas fa-store-alt-slash empty-icon"></i>
                <p>没有找到符合条件的商店</p>
            </div>

            <router-link v-else v-for="store in filteredStores" :key="store.storeId" :to="`/store/${store.storeId}`"
                class="store-card">
                <img class="store-image" :src="store.coverImage || getRandomDefaultImage()" :alt="store.name">
                <div class="store-content">
                    <div class="store-header">
                        <div class="store-name">{{ store.name }}</div>
                        <div class="store-rating">
                            <i class="fas fa-star"></i>
                            <span class="store-rating-score">{{ store.rating.toFixed(1) == 0 ? '暂无评分' : store.rating.toFixed(1) }}</span>
                        </div>
                    </div>
                    <div class="store-info">
                        <i class="fas fa-map-marker-alt"></i>
                        <span>{{ store.address }}</span>
                    </div>
                    <div class="store-tags">
                        <span class="store-tag" v-for="tag in store.tags" :key="tag.tagId">{{ tag.name }}</span>
                    </div>
                    <div class="store-distance">
                        <span :class="['store-hours', { closed: !isStoreOpen(store.businessHours) }]">
                            {{ isStoreOpen(store.businessHours) ? '营业中' : '已关闭' }}
                        </span>
                        <span v-if="store.distance" class="distance-value">{{ store.distance.toFixed(2) }} km</span>
                    </div>
                </div>
            </router-link>
        </div>

        <!-- 底部导航 -->
        <TabBar activeTab="store" />
    </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import api from '@/network/api';
import TabBar from '@/components/TabBar.vue';

export default {
    name: 'StoreListView',
    components: {
        TabBar
    },
    setup() {
        const router = useRouter();
        const stores = ref([]);
        const loading = ref(true);
        const searchQuery = ref('');
        const currentFilter = ref(0);
        const userLocation = ref({ latitude: 0, longitude: 0 });
        const storeTags = ref([]);

        // 获取随机默认图片
        const getRandomDefaultImage = () => {
            const imageNumber = Math.floor(Math.random() * 4) + 1;
            return `/image/store_cover/${imageNumber}.png`;
        };

        // 过滤选项
        const filters = computed(() => {
            const staticFilters = [
                { name: '全部', value: 0 },
            ];
            const dynamicFilters = storeTags.value.map(tag => ({
                name: tag.name,
                value: tag.tagId,
            }));
            return [...staticFilters, ...dynamicFilters];
        });

        // 获取商店列表
        const fetchStores = async () => {
            loading.value = true;
            try {
                const response = await api.getStores(currentFilter.value || 0);
                const storesData = response.data.data || [];
                stores.value = await Promise.all(storesData.map(async store => {
                    store.tags = await getStoreTags(store.storeId);
                    // 计算距离
                    if (userLocation.value.latitude && userLocation.value.longitude) {
                        store.distance = calculateDistance(
                            userLocation.value.latitude,
                            userLocation.value.longitude,
                            store.latitude,
                            store.longitude
                        );
                    } else {
                        store.distance = null;
                    }
                    return store;
                }));
            } catch (error) {
                console.error('获取商店列表失败:', error);
            } finally {
                loading.value = false;
            }
        };

        const fetchStoreCategories = async () => {
            try {
                const response = await api.getStoreTags();
                if (response.data && response.data.data) {
                    storeTags.value = response.data.data;
                }
            } catch (error) {
                console.error('获取商店分类失败:', error);
            }
        };

        const getStoreTags = async (id) => {
            if (!id) return [];
            try {
                const response = await api.getStoreTagsById(id);
                return response.data.data || [];
            } catch (error) {
                console.error(`获取商店 ${id} 的标签失败:`, error);
                return [];
            }
        };

        // 判断商店是否营业中
        const isStoreOpen = (businessHours) => {
            if (!businessHours || typeof businessHours !== 'string') return false;

            const now = new Date();
            // JS getDay(): Sun=0, Mon=1, ..., Sat=6.
            // 营业时间格式似乎是 Mon=1, ..., Sat=6, Sun=7.
            let dayOfWeek = now.getDay();
            if (dayOfWeek === 0) {
                dayOfWeek = 7; // 将周日转换为7以匹配格式
            }

            const currentTotalMinutes = now.getHours() * 60 + now.getMinutes();

            try {
                const schedules = businessHours.split(',');

                for (const schedule of schedules) {
                    const firstColonIndex = schedule.indexOf(':');
                    if (firstColonIndex === -1) continue;

                    const daysPart = schedule.substring(0, firstColonIndex);
                    const hoursPart = schedule.substring(firstColonIndex + 1);

                    let dayStart, dayEnd;
                    if (daysPart.includes('-')) {
                        [dayStart, dayEnd] = daysPart.split('-').map(Number);
                    } else {
                        dayStart = dayEnd = Number(daysPart);
                    }

                    if (dayOfWeek >= dayStart && dayOfWeek <= dayEnd) {
                        const [timeStartStr, timeEndStr] = hoursPart.split('-');
                        const [startHour, startMinute] = timeStartStr.split(':').map(Number);
                        const [endHour, endMinute] = timeEndStr.split(':').map(Number);

                        const openTimeInMinutes = startHour * 60 + startMinute;
                        const closeTimeInMinutes = endHour * 60 + endMinute;

                        if (currentTotalMinutes >= openTimeInMinutes && currentTotalMinutes <= closeTimeInMinutes) {
                            return true; // 商店正在营业
                        }
                    }
                }
            } catch (error) {
                console.error('解析营业时间出错:', businessHours, error);
                return false; // 解析失败则认为已关闭
            }

            return false; // 商店已关闭
        };

        // 根据过滤条件和搜索词过滤商店
        const filteredStores = computed(() => {
            let result = stores.value;

            // 应用搜索过滤
            if (searchQuery.value) {
                const query = searchQuery.value.toLowerCase();
                result = result.filter(store =>
                    store.name.toLowerCase().includes(query) ||
                    store.address.toLowerCase().includes(query)
                );
            }

            // 应用标签过滤
            const filterValue = currentFilter.value;
            if (filterValue !== 0) {
                // 后端已过滤，前端不再需要此逻辑
            }

            return result;
        });

        // 设置过滤条件
        const setFilter = (filter) => {
            currentFilter.value = filter;
            if (userLocation.value.latitude && userLocation.value.longitude) {
                fetchNearbyStores();
            } else {
                fetchStores();
            }
        };

        // 处理搜索
        const handleSearch = () => {
            // 可以在这里实现搜索防抖等逻辑
        };

        // 返回上一页
        const goBack = () => {
            router.back();
        };

        const refreshStoreRating = async () => {
            const response = await api.refreshStoreRating();
        }

        onMounted(async () => {
            refreshStoreRating();
            // 先获取分类，再获取商店列表
            await fetchStoreCategories();
            fetchStores();
        });

        return {
            stores,
            loading,
            searchQuery,
            currentFilter,
            filters,
            filteredStores,
            setFilter,
            handleSearch,
            isStoreOpen,
            getRandomDefaultImage,
            goBack
        };
    }
}
</script>

<style scoped>
.store-list-container {
    display: flex;
    flex-direction: column;
    height: 100%;
    background-color: #f8fafc;
}

.navbar {
    position: sticky;
    top: 0;
    z-index: 50;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background-color: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(5px);
    -webkit-backdrop-filter: blur(5px);
    border-bottom: 1px solid #f1f5f9;
}

.navbar-back {
    color: #333;
    font-size: 16px;
}

.navbar-title {
    font-weight: 600;
    font-size: 18px;
}

.text-primary {
    color: #3490dc;
    font-size: 18px;
}

.header {
    padding: 15px;
    background-color: white;
    border-bottom: 1px solid #f1f5f9;
    position: sticky;
    top: 58px;
    z-index: 40;
}

.search-bar {
    display: flex;
    align-items: center;
    background-color: #f1f5f9;
    border-radius: 10px;
    padding: 10px 15px;
}

.search-icon {
    color: #94a3b8;
    margin-right: 10px;
}

.search-input {
    border: none;
    background-color: transparent;
    outline: none;
    flex: 1;
    font-size: 14px;
}

.filter-bar {
    display: flex;
    padding: 12px 15px;
    overflow-x: auto;
    background-color: white;
    border-bottom: 1px solid #f1f5f9;
    position: sticky;
    top: 124px;
    z-index: 30;
    scrollbar-width: none;
}

.filter-bar::-webkit-scrollbar {
    display: none;
}

.filter-btn {
    padding: 8px 16px;
    background-color: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 500;
    color: #4a5568;
    margin-right: 10px;
    white-space: nowrap;
    cursor: pointer;
    transition: all 0.2s ease-in-out;
}

.filter-btn:hover {
    border-color: #3490dc;
    color: #3490dc;
}

.filter-btn.active {
    background-color: #3490dc;
    color: white;
    border-color: #3490dc;
}

.store-list {
    flex: 1;
    padding: 15px;
    padding-bottom: 80px;
    background-color: #f8fafc;
    overflow-y: auto;
    height: 100%;
}

.store-card {
    display: flex;
    padding: 16px;
    background-color: white;
    border-radius: 12px;
    margin-bottom: 16px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.06);
    text-decoration: none;
    color: inherit;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.store-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 6px 16px rgba(0,0,0,0.1);
}

.store-image {
    width: 90px;
    height: 90px;
    border-radius: 10px;
    object-fit: cover;
    margin-right: 16px;
    flex-shrink: 0;
}

.store-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-width: 0;
}

.store-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 8px;
}

.store-name {
    font-weight: 600;
    font-size: 17px;
    color: #1e293b;
    margin-right: 8px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.store-rating {
    display: flex;
    align-items: center;
    color: #f59e0b;
    font-size: 14px;
    font-weight: 600;
    flex-shrink: 0;
}

.store-rating-score {
    margin-left: 4px;
    color: #1e293b;
}

.store-info {
    font-size: 13px;
    color: #64748b;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.store-info i {
    margin-right: 6px;
    color: #94a3b8;
}

.store-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin-bottom: auto;
    padding-bottom: 8px;
}

.store-tag {
    display: inline-block;
    padding: 3px 10px;
    background-color: #f1f5f9;
    border-radius: 999px;
    font-size: 11px;
    font-weight: 500;
    color: #475569;
}

.store-distance {
    font-size: 13px;
    color: #4a5568;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 8px;
}

.distance-value {
    font-weight: 500;
}

.store-hours {
    font-weight: 500;
    color: #10b981;
}

.store-hours.closed {
    color: #ef4444;
}

.loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-top: 50px;
}

.loading-spinner {
    border: 3px solid #f3f3f3;
    border-top: 3px solid #3490dc;
    border-radius: 50%;
    width: 30px;
    height: 30px;
    animation: spin 1s linear infinite;
    margin-bottom: 10px;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

.loading-text {
    color: #718096;
    font-size: 14px;
}

.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-top: 50px;
    color: #a0aec0;
}

.empty-icon {
    font-size: 48px;
    margin-bottom: 16px;
}
</style>
